package mspbots.cw.business.core.opportunities;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.business.core.BaseReceiver;
import mspbots.cw.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @author Jay.Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class OpportunitiesReceiver extends BaseReceiver {

    private final OpportunitiesRepository opportunitiesRepository;

//    @RabbitListener(queues = "connect-wise.opportunities.tl")
    public void process(ResultMsg resultMsg) {
        JsonNode entity = resultMsg.getEntity();
        Opportunities data = super.objectMapper.convertValue(entity, Opportunities.class);
        data.setId(null);
        data.setCwId(resultMsg.getId());
        data.setTenantCode(resultMsg.getTenantId());
        data.setSyncTime(resultMsg.getSyncDate());
        data.setUpdatedBy(super.getStringValue(entity.findValue("updatedBy")));
        data.setLastUpdated(super.getDateTimeValue(entity.findValue("lastUpdated")));
        data.setCompanyName(super.getStringValueName(entity.get("company")));
        data.setContactName(super.getStringValueName(entity.get("contact")));
        data.setTypeName(super.getStringValueName(entity.get("type")));
        data.setStatusName(super.getStringValueName(entity.get("status")));
        data.setStageName(super.getStringValueName(entity.get("stage")));
        data.setRatingName(super.getStringValueName(entity.get("rating")));
        data.setProbabilityName(super.getStringValueName(entity.get("probability")));
        data.setClosedByIdentifier(super.getStringValueIdentifier(entity.get("closedBy")));
        data.setPrimarySalesRepName(super.getStringValueName(entity.get("primarySalesRep")));
        data.setSecondarySalesRepName(super.getStringValueName(entity.get("secondarySalesRep")));
        data.setCampaignName(super.getStringValueName(entity.get("campaign")));

        this.opportunitiesRepository.findByCwIdAndTenantCode(resultMsg.getId(), resultMsg.getTenantId())
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.opportunitiesRepository::save).block(Duration.ofSeconds(10));
    }

}
